%% 构建完整的10kV星接级联H桥SVG储能系统模型
function build_complete_svg_model()
    % 初始化参数
    SVG_Star_10kV_System_Init;
    
    % 创建主模型
    model_name = 'SVG_Star_10kV_Complete';
    if bdIsLoaded(model_name)
        close_system(model_name, 0);
    end
    new_system(model_name);
    open_system(model_name);
    
    % 设置模型参数
    set_param(model_name, 'Solver', 'ode23tb');
    set_param(model_name, 'MaxStep', '1e-5');
    set_param(model_name, 'StopTime', '3');
    
    %% 1. 添加PowerGUI（必需）
    add_block('sps_lib/powergui', [model_name '/powergui']);
    set_param([model_name '/powergui'], 'Position', [50 20 120 70]);
    set_param([model_name '/powergui'], 'SimulationMode', 'Discrete');
    set_param([model_name '/powergui'], 'SampleTime', '1e-5');
    
    %% 2. 创建电网系统
    create_grid_system(model_name);
    
    %% 3. 创建星接级联H桥SVG
    create_star_svg_system(model_name);
    
    %% 4. 创建储能系统
    create_storage_system(model_name);
    
    %% 5. 创建负载系统
    create_load_system(model_name);
    
    %% 6. 创建控制系统
    create_control_blocks(model_name);
    
    %% 7. 创建测量和显示系统
    create_measurement_display(model_name);
    
    %% 8. 连接所有子系统
    connect_subsystems(model_name);
    
    % 保存模型
    save_system(model_name);
    fprintf('完整模型 %s 创建成功！\n', model_name);
end

%% 子函数：创建电网系统
function create_grid_system(model_name)
    load('SVG_Parameters.mat');
    
    % 强电网源
    add_block('sps_lib/Sources/Three-Phase Source', [model_name '/Strong_Grid']);
    set_param([model_name '/Strong_Grid'], 'Position', [100 100 150 150]);
    set_param([model_name '/Strong_Grid'], 'Voltage', num2str(Vgrid_LL));
    set_param([model_name '/Strong_Grid'], 'InternalConnection', 'Yg');
    
    % 弱电网源（光伏）
    add_block('sps_lib/Sources/Three-Phase Source', [model_name '/Weak_Grid_PV']);
    set_param([model_name '/Weak_Grid_PV'], 'Position', [100 200 150 250]);
    set_param([model_name '/Weak_Grid_PV'], 'Voltage', num2str(Vgrid_LL));
    set_param([model_name '/Weak_Grid_PV'], 'InternalConnection', 'Yg');
    
    % 强电网阻抗
    add_block('sps_lib/Passives/Three-Phase Series RLC Branch', [model_name '/Strong_Grid_Z']);
    set_param([model_name '/Strong_Grid_Z'], 'Position', [200 100 250 130]);
    set_param([model_name '/Strong_Grid_Z'], 'BranchType', 'L');
    set_param([model_name '/Strong_Grid_Z'], 'Inductance', num2str(L_grid_strong));
    
    % 弱电网阻抗
    add_block('sps_lib/Passives/Three-Phase Series RLC Branch', [model_name '/Weak_Grid_Z']);
    set_param([model_name '/Weak_Grid_Z'], 'Position', [200 200 250 230]);
    set_param([model_name '/Weak_Grid_Z'], 'BranchType', 'L');
    set_param([model_name '/Weak_Grid_Z'], 'Inductance', num2str(L_grid_weak));
    
    % 电网切换开关
    add_block('sps_lib/Power Grid Elements/Three-Phase Breaker', [model_name '/Grid_Selector']);
    set_param([model_name '/Grid_Selector'], 'Position', [300 150 350 180]);
end

%% 子函数：创建星接级联H桥SVG系统
function create_star_svg_system(model_name)
    load('SVG_Parameters.mat');
    
    % 创建SVG子系统
    add_block('built-in/Subsystem', [model_name '/Star_SVG']);
    set_param([model_name '/Star_SVG'], 'Position', [500 100 700 300]);
    
    svg_subsys = [model_name '/Star_SVG'];
    
    % 三相输入端口
    add_block('built-in/Inport', [svg_subsys '/Grid_Connection']);
    set_param([svg_subsys '/Grid_Connection'], 'Position', [50 150 80 170]);
    
    % 为每相创建级联H桥
    phases = {'A', 'B', 'C'};
    for i = 1:3
        % 创建相子系统
        phase_subsys = [svg_subsys '/Phase_' phases{i}];
        add_block('built-in/Subsystem', phase_subsys);
        set_param(phase_subsys, 'Position', [200+150*(i-1) 100 300+150*(i-1) 200]);
        
        % 在相子系统中创建11个H桥
        for j = 1:N_bridge
            % H桥模块
            hbridge = [phase_subsys '/HBridge_' num2str(j)];
            add_block('sps_lib/Power Electronics/Universal Bridge', hbridge);
            set_param(hbridge, 'Position', [100 50+80*(j-1) 200 100+80*(j-1)]);
            set_param(hbridge, 'Arms', '2');
            set_param(hbridge, 'Device', 'IGBT / Diodes');
            set_param(hbridge, 'Ron', '1e-3');
            set_param(hbridge, 'SnubberResistance', 'inf');
            
            % 直流电容
            cap = [phase_subsys '/DC_Cap_' num2str(j)];
            add_block('sps_lib/Passives/Series RLC Branch', cap);
            set_param(cap, 'Position', [250 60+80*(j-1) 280 90+80*(j-1)]);
            set_param(cap, 'BranchType', 'C');
            set_param(cap, 'Capacitance', '2e-3');
            
            % 电压测量
            vmeas = [phase_subsys '/Vdc_Meas_' num2str(j)];
            add_block('sps_lib/Sensors and Measurements/Voltage Measurement', vmeas);
            set_param(vmeas, 'Position', [320 60+80*(j-1) 350 90+80*(j-1)]);
        end
    end
    
    % 星形连接点（中性点）
    % 使用电气参考点（接地）
    % 注意：根据MATLAB版本，Ground模块的路径可能不同
    % 尝试以下几种可能的路径：
    try
        % 路径1: 新版本MATLAB
        add_block('nesl_utility/Ground', [svg_subsys '/Neutral_Ground']);
    catch
        try
            % 路径2: SimPowerSystems
            add_block('powerlib/Elements/Ground', [svg_subsys '/Neutral_Ground']);
        catch
            % 路径3: 使用三相中性点
            add_block('sps_lib/Elements/Neutral', [svg_subsys '/Neutral_Ground']);
        end
    end
    set_param([svg_subsys '/Neutral_Ground'], 'Position', [400 300 430 330]);
    
    % 输出端口
    add_block('built-in/Outport', [svg_subsys '/SVG_Output']);
    set_param([svg_subsys '/SVG_Output'], 'Position', [600 150 630 170]);
end

%% 子函数：创建储能系统
function create_storage_system(model_name)
    load('SVG_Parameters.mat');
    
    % 创建储能子系统
    add_block('built-in/Subsystem', [model_name '/Energy_Storage']);
    set_param([model_name '/Energy_Storage'], 'Position', [500 350 700 450]);
    
    storage_subsys = [model_name '/Energy_Storage'];
    
    % 为每相每个H桥创建超级电容和DC/DC
    phases = {'A', 'B', 'C'};
    for i = 1:3
        for j = 1:N_bridge
            % 超级电容模型
            sc_subsys = [storage_subsys '/SC_' phases{i} num2str(j)];
            add_block('built-in/Subsystem', sc_subsys);
            set_param(sc_subsys, 'Position', [100+60*(i-1) 50+30*(j-1) 140+60*(i-1) 70+30*(j-1)]);
            
            % 在超级电容子系统内部
            % 电容
            add_block('sps_lib/Passives/Series RLC Branch', [sc_subsys '/SC']);
            set_param([sc_subsys '/SC'], 'BranchType', 'C');
            set_param([sc_subsys '/SC'], 'Capacitance', num2str(C_sc));
            
            % ESR
            add_block('sps_lib/Passives/Series RLC Branch', [sc_subsys '/ESR']);
            set_param([sc_subsys '/ESR'], 'BranchType', 'R');
            set_param([sc_subsys '/ESR'], 'Resistance', '0.01');
            
            % 初始电压
            add_block('sps_lib/Sources/DC Voltage Source', [sc_subsys '/V_init']);
            set_param([sc_subsys '/V_init'], 'Amplitude', num2str(Vsc_rated * SOC_init));
            
            % DC/DC变换器（简化模型）
            dcdc_subsys = [storage_subsys '/DCDC_' phases{i} num2str(j)];
            add_block('built-in/Subsystem', dcdc_subsys);
            set_param(dcdc_subsys, 'Position', [200+60*(i-1) 50+30*(j-1) 240+60*(i-1) 70+30*(j-1)]);
        end
    end
end

%% 子函数：创建负载系统
function create_load_system(model_name)
    load('SVG_Parameters.mat');
    
    % 混合负载子系统
    add_block('built-in/Subsystem', [model_name '/Mixed_Load']);
    set_param([model_name '/Mixed_Load'], 'Position', [850 150 1050 250]);
    
    load_subsys = [model_name '/Mixed_Load'];
    
    % 工业负载（60%）- 使用Three-Phase Series RLC Load替代
    add_block('sps_lib/Passives/Three-Phase Series RLC Load', [load_subsys '/Industrial']);
    set_param([load_subsys '/Industrial'], 'Position', [100 50 200 100]);
    set_param([load_subsys '/Industrial'], 'NominalVoltage', num2str(Vgrid_LL));
    set_param([load_subsys '/Industrial'], 'ActivePower', num2str(P_industrial));
    set_param([load_subsys '/Industrial'], 'InductivePower', num2str(P_industrial * 0.55));
    set_param([load_subsys '/Industrial'], 'CapacitivePower', '0');
    
    % 商业负载（26%）
    add_block('sps_lib/Passives/Three-Phase Series RLC Load', [load_subsys '/Commercial']);
    set_param([load_subsys '/Commercial'], 'Position', [100 150 200 200]);
    set_param([load_subsys '/Commercial'], 'NominalVoltage', num2str(Vgrid_LL));
    set_param([load_subsys '/Commercial'], 'ActivePower', num2str(P_commercial));
    set_param([load_subsys '/Commercial'], 'InductivePower', num2str(P_commercial * 0.2));
    set_param([load_subsys '/Commercial'], 'CapacitivePower', num2str(P_commercial * 0.06));
    
    % 居民负载（14%）
    add_block('sps_lib/Passives/Three-Phase Series RLC Load', [load_subsys '/Residential']);
    set_param([load_subsys '/Residential'], 'Position', [100 250 200 300]);
    set_param([load_subsys '/Residential'], 'NominalVoltage', num2str(Vgrid_LL));
    set_param([load_subsys '/Residential'], 'ActivePower', num2str(P_residential));
    set_param([load_subsys '/Residential'], 'CapacitivePower', num2str(P_residential * 0.34));
    
    % 负载连接点
    % 注意：Bus Bar模块路径可能因版本而异，这里我们用一个简单的方法
    % 创建一个三相连接点（可以是一个空的子系统或使用三相测量点）
    try
        % 方法1: 尝试使用T connector
        add_block('sps_lib/Connectors/T connector', [load_subsys '/Load_Connection']);
    catch
        try
            % 方法2: 使用三相电压测量作为连接点
            add_block('sps_lib/Sensors and Measurements/Three-Phase V-I Measurement', [load_subsys '/Load_Connection']);
            set_param([load_subsys '/Load_Connection'], 'VoltageMeasurement', 'no');
            set_param([load_subsys '/Load_Connection'], 'CurrentMeasurement', 'no');
        catch
            % 方法3: 创建一个空的子系统作为连接点
            add_block('built-in/Subsystem', [load_subsys '/Load_Connection']);
            % 在子系统内添加三相端口
            load_conn = [load_subsys '/Load_Connection'];
            add_block('built-in/Inport', [load_conn '/Phase_ABC']);
            add_block('built-in/Outport', [load_conn '/Load_Out']);
        end
    end
    set_param([load_subsys '/Load_Connection'], 'Position', [300 175 400 185]);
end

%% 子函数：创建控制系统
function create_control_blocks(model_name)
    % 主控制系统
    add_block('built-in/Subsystem', [model_name '/Control_System']);
    set_param([model_name '/Control_System'], 'Position', [400 500 800 700]);
    
    ctrl_subsys = [model_name '/Control_System'];
    
    % SCR检测
    add_block('built-in/Subsystem', [ctrl_subsys '/SCR_Detection']);
    set_param([ctrl_subsys '/SCR_Detection'], 'Position', [100 50 200 100]);
    
    % 模式切换控制
    add_block('built-in/Subsystem', [ctrl_subsys '/Mode_Control']);
    set_param([ctrl_subsys '/Mode_Control'], 'Position', [250 50 350 100]);
    
    % PLL（跟网模式）
    add_block('built-in/Subsystem', [ctrl_subsys '/PLL']);
    set_param([ctrl_subsys '/PLL'], 'Position', [100 150 200 200]);
    
    % VSM控制（构网模式）
    add_block('built-in/Subsystem', [ctrl_subsys '/VSM_Control']);
    set_param([ctrl_subsys '/VSM_Control'], 'Position', [250 150 350 200]);
    
    % 功率控制
    add_block('built-in/Subsystem', [ctrl_subsys '/Power_Control']);
    set_param([ctrl_subsys '/Power_Control'], 'Position', [100 250 200 300]);
    
    % 电流控制
    add_block('built-in/Subsystem', [ctrl_subsys '/Current_Control']);
    set_param([ctrl_subsys '/Current_Control'], 'Position', [250 250 350 300]);
    
    % 电压均衡控制
    add_block('built-in/Subsystem', [ctrl_subsys '/Voltage_Balance']);
    set_param([ctrl_subsys '/Voltage_Balance'], 'Position', [400 150 500 200]);
    
    % SOC均衡控制
    add_block('built-in/Subsystem', [ctrl_subsys '/SOC_Balance']);
    set_param([ctrl_subsys '/SOC_Balance'], 'Position', [400 250 500 300]);
    
    % PWM调制
    add_block('built-in/Subsystem', [ctrl_subsys '/PWM_Generation']);
    set_param([ctrl_subsys '/PWM_Generation'], 'Position', [550 200 650 250]);
end

%% 子函数：创建测量和显示系统
function create_measurement_display(model_name)
    % 测量系统
    add_block('built-in/Subsystem', [model_name '/Measurements']);
    set_param([model_name '/Measurements'], 'Position', [900 400 1100 600]);
    
    meas_subsys = [model_name '/Measurements'];
    
    % 电网测量
    add_block('sps_lib/Sensors and Measurements/Three-Phase V-I Measurement', ...
              [meas_subsys '/Grid_VI']);
    set_param([meas_subsys '/Grid_VI'], 'Position', [100 50 150 100]);
    
    % SVG测量
    add_block('sps_lib/Sensors and Measurements/Three-Phase V-I Measurement', ...
              [meas_subsys '/SVG_VI']);
    set_param([meas_subsys '/SVG_VI'], 'Position', [100 150 150 200]);
    
    % 负载测量
    add_block('sps_lib/Sensors and Measurements/Three-Phase V-I Measurement', ...
              [meas_subsys '/Load_VI']);
    set_param([meas_subsys '/Load_VI'], 'Position', [100 250 150 300]);
    
    % 功率计算
    add_block('sps_lib/Sensors and Measurements/Power (3ph, Instantaneous)', ...
              [meas_subsys '/Power_Calc']);
    set_param([meas_subsys '/Power_Calc'], 'Position', [250 150 350 200]);
    
    % THD分析
    add_block('sps_lib/Sensors and Measurements/THD', [meas_subsys '/THD_Grid']);
    set_param([meas_subsys '/THD_Grid'], 'Position', [250 250 350 300]);
    
    % 显示系统
    add_block('built-in/Subsystem', [model_name '/Display_System']);
    set_param([model_name '/Display_System'], 'Position', [1150 100 1350 700]);
    
    disp_subsys = [model_name '/Display_System'];
    
    % Scope显示
    scopes = {'Grid_Voltage', 'Grid_Current', 'SVG_Voltage', 'SVG_Current', ...
              'Power_PQ', 'DC_Voltage', 'SOC', 'SCR', 'THD'};
    
    for i = 1:length(scopes)
        add_block('built-in/Scope', [disp_subsys '/' scopes{i} '_Scope']);
        set_param([disp_subsys '/' scopes{i} '_Scope'], ...
                  'Position', [100 50+60*(i-1) 200 90+60*(i-1)]);
    end
    
    % 数据记录
    add_block('simulink/Sinks/To Workspace', [disp_subsys '/Data_Logger']);
    set_param([disp_subsys '/Data_Logger'], 'Position', [300 300 400 350]);
    set_param([disp_subsys '/Data_Logger'], 'VariableName', 'SimData');
end

%% 子函数：连接所有子系统
function connect_subsystems(model_name)
    % 这里添加连接逻辑
    % 由于连接较复杂，实际使用时需要在Simulink中手动连接或使用add_line命令
    
    fprintf('请在Simulink中手动连接各子系统，或运行自动连接脚本。\n');
end